<?php

namespace app\index\controller;

use app\index\model\Cart;
use app\index\model\Goods;
use app\index\model\LogisticsCompany;
use app\index\model\OrderDetail;
use app\index\model\Orders;
use app\index\model\Pictures;
use app\index\model\Spu;
use app\index\model\Users;
use think\Controller;

class OrderCtl extends Controller
{
    /*
     * 获取所有订单，进行订单管理
     */
    public function getOrders()
    {
        $page = input('page', 1);
        $pageSize = input('pageSize', 12);
        $orders = Orders::with('detail')->page($page, $pageSize)->select();
        foreach ($orders as $order) {
            $order['user'] = Users::where('id', $order['uid'])->field('username, phone')->find();
            foreach ($order['detail'] as $o) {
                $o['spu'] = Spu::where('id', $o['spuid'])->find();
                $o['goods'] = Goods::where('id', $o['spu']['gid'])->field('id,name')->find();
                $o['picture'] = Pictures::where(['gid' => $o['goods']['id'], 'type' => 0])->value('url');
                $o['sku'] = setOrderSku($o['spuid']);
            }
        }
        $res['totalPage'] = ceil(Orders::count('id') / $pageSize);
        $res['data'] = $orders;
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 直接购买商品时，需要构造出购物车形式的数据，方便前端展示
     */
    public function getSelectedSpuInfo()
    {
        $res['spu'] = Spu::with('goods')->where('id', input('spu_id'))->find();
        $res['sku'] = setOrderSku(input('spu_id'));
        $res['picture'] = Pictures::where(['gid' => $res['spu']['gid'], 'type' => 0])->value('url');
        $res['amount'] = 1;
        $res['checked'] = true;
        return json([$res]);
    }

    /*
     * 下单
     */
    public function addOrder()
    {
        $newOrder = Orders::create([
            'uid' => input('uid'),
            'tprice' => input('tprice'),
            'address' => input('address'),
            'order_time' => time()
        ]);
        // 下单后删除对应购物车记录
        $cartIds = input('cartIds');
        if ($cartIds != null) {
            Cart::destroy($cartIds);
        }
        $goods = json_decode(stripslashes(html_entity_decode(input('goods'))), true);
        // 将订单中的商品（可能有多条）插入数据库
        $newOrder->detail()->saveAll($goods);
        return json(['msg' => '添加成功！', 'order_id' => $newOrder->id]);
    }

    /*
     * 删除订单
     */
    public function delOrder()
    {
        $order = Orders::get(input('id'), 'detail');
        $order->together('detail')->delete();
        return json(['msg' => '删除成功！']);
    }

    /*
     * 获取用户的订单记录
     */
    public function getByUid()
    {
        $orders = Orders::where('uid', input('uid'))->with('detail')->select();
        foreach ($orders as $order) {
            foreach ($order['detail'] as $o) {
                $o['spu'] = Spu::where('id', $o['spuid'])->find();
                $o['goods'] = Goods::where('id', $o['spu']['gid'])->find();
                $o['picture'] = Pictures::where(['gid' => $o['goods']['id'], 'type' => 0])->value('url');
                $o['sku'] = setOrderSku($o['spuid']);
            }
        }
        return json($orders);
    }

    /*
     * 付款
     */
    public function doPay()
    {
        Orders::update([
            'id' => input('id'),
            'pay_time' => time(),
            'pay_status' => 1,
            'pay_way' => input('pay_way')
        ]);
        return json(['msg' => '支付成功！']);
    }

    /*
     * 发货
     */
    public function doDelivery()
    {
        Orders::update([
            'id' => input('id'),
            'delivery_time' => time(),
            'delivery_status' => 1,
            'delivery_company' => input('delivery_company')
        ]);
        $spuIds = OrderDetail::where('order_id', input('id'))->column('spuid');
        foreach ($spuIds as $spuId) {
            $gid = Spu::where('id', $spuId)->value('gid');
            Goods::where('id', $gid)->setInc('payments');
        }
        return json(['msg' => '发货成功！', 'code' => 20000]);
    }

    /*
     * 获取所有物流公司
     */
    public function getLogisticsCompany()
    {
        $res['data'] = LogisticsCompany::select();
        $res['code'] = 20000;
        return json($res);
    }
}